package com.testingedu.action.background;

import java.io.File;

import javax.servlet.ServletContext;

import com.testingedu.jdbcDao.TRoleDao;
import com.testingedu.jdbcDao.TRoleInUserDao;
import com.testingedu.jdbcDao.TUserDao;
import com.testingedu.model.FileInfo;
import com.testingedu.model.TUser;
import com.testingedu.utils.FileUtils;
import com.testingedu.utils.Md5;

public class TUserAction extends RequestContext {
	private static final long serialVersionUID = 8327331606715047261L;
	private TUser tUser;
	private static TUserDao tUserDao = new TUserDao();
	private FileInfo uploadFile;
	private static final String PHOTO_DIR = File.separator + "upload"
			+ File.separator + "head";
	private ServletContext servletContext;

	public void setServletContext(ServletContext servletContext) {
		this.servletContext = servletContext;
	}

	public FileInfo getUploadFile() {
		return uploadFile;
	}

	public void setUploadFile(FileInfo uploadFile) {
		this.uploadFile = uploadFile;
	}

	public void settUser(TUser tUser) {
		this.tUser = tUser;
	}

	private boolean accountAndPassIsNull() {
		if (tUser == null)
			return true;
		if (tUser.getAccount() == null || tUser.getPassword() == null)
			return true;
		return false;
	}

	public void _login() throws Exception {
		if (accountAndPassIsNull()) {
			request.setAttribute("errorMessage", "请填写用户名和密码");
			request.getRequestDispatcher("/WEB-INF/admin/jsp/login.jsp")
					.forward(request, response);
		} else {
			TUser sessionUser = tUserDao.login(tUser);
			if (sessionUser == null) {
				request.setAttribute("errorMessage", "用户名或密码错误");
				request.getRequestDispatcher("/WEB-INF/admin/jsp/login.jsp")
						.forward(request, response);
			} else {
				String yzmForm = request.getParameter("yzm");
				String yzmSession = (String) request.getSession().getAttribute(
						"yanZhengMaKey");
				if (!yzmForm.equals(yzmSession)) {
					request.setAttribute("errorMessage", "验证码错误");
					request
							.getRequestDispatcher(
									"/WEB-INF/admin/jsp/login.jsp").forward(
									request, response);
				} else {
					request.getSession().setAttribute("testingedu_admin",
							sessionUser);
					request.getRequestDispatcher("/WEB-INF/admin/jsp/main.jsp")
							.forward(request, response);
				}
			}
		}
	}

	public void _add() throws Exception {
		String url = request.getParameter("url");
		if ("jsp".equals(url)) {
			createQueryResult();
			new TRoleDao().list(queryResult, null);
			request.setAttribute("queryResult", queryResult);
			request.getRequestDispatcher("/WEB-INF/admin/jsp/user/add.jsp")
					.forward(request, response);
		} else {
			if (uploadFile != null && uploadFile.getFile() != null
					&& uploadFile.getFile().length > 0) {
				File tempFile = uploadFile.getFile()[0];
				String dir = servletContext.getRealPath(PHOTO_DIR);
				String filePath = dir + File.separator
						+ uploadFile.getName()[0];
				String dbPath = (PHOTO_DIR + File.separator + uploadFile
						.getName()[0]).replaceAll("\\\\", "/");
				tUser.setPhotoPath(dbPath);
				File dstFile = new File(filePath);
				FileUtils.copy(tempFile, dstFile);
				File deleteFolder = new File(tempFile.getAbsolutePath()
						.substring(
								0,
								tempFile.getAbsolutePath().lastIndexOf(
										File.separatorChar)));
				org.apache.commons.io.FileUtils.deleteDirectory(deleteFolder);
			} else {
				tUser.setPhotoPath("/");
			}
			tUser.setCertificateId("无");
			tUser.setCertificateName("无");
			int userId = tUserDao.add(tUser);
			if (tUser.getRoleId() != null && tUser.getRoleId() > 0
					&& userId > 0) {
				new TRoleInUserDao().add(userId, tUser.getRoleId());
			}
			response.getWriter().write("{\"id\":" + userId + "}");
			response.getWriter().close();
		}
	}

	public void _delete() throws Exception {
		tUserDao.delete(tUser.getId());
		response.sendRedirect("/testingedu2/admin/user/list");
	}

	public void _update() {
		try {
			String url = request.getParameter("url");
			if ("update".equals(url)) {
				createQueryResult();
				new TRoleDao().list(queryResult, tUser.getId());
				request.setAttribute("queryResult", queryResult);
				request.setAttribute("tUser", tUserDao.info(tUser.getId()));
				request.getRequestDispatcher("/WEB-INF/admin/jsp/user/update.jsp")
						.forward(request, response);
			} else {
				String url_1 = request.getParameter("url_1");
				if ("pass".equals(url) && "jsp".equals(url_1)) {
					request.getRequestDispatcher(
							"/WEB-INF/admin/jsp/user/updatePass.jsp").forward(
							request, response);
				} else if ("resetPass".equals(url)) {
					String newPass = tUserDao.resetPass(tUser.getId());
					response.getWriter().write("{\"newPass\":\"" + newPass + "\"}");
					response.getWriter().close();
				} else {
					tUserDao.update(tUser);
					response.getWriter().write("{\"id\":" + tUser.getId() + "}");
					response.getWriter().close();
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public void _list() throws Exception {
		String url = request.getParameter("url");
		if ("info".equals(url)) {
			tUser = tUserDao.info(tUser.getId());
			request.setAttribute("tUser", tUserDao.info(tUser.getId()));
			request.getRequestDispatcher("/WEB-INF/admin/jsp/user/info.jsp")
					.forward(request, response);
		} else {
			createQueryResult();
			tUserDao.list(queryResult, tUser);
			request.setAttribute("queryResult", queryResult);
			request.getRequestDispatcher("/WEB-INF/admin/jsp/user/list.jsp")
					.forward(request, response);
		}
	}

	/**
	 * 用户退出系统
	 * 
	 * @throws Exception
	 */
	public void _exit() throws Exception {
		request.getSession().removeAttribute("testingedu_admin");
		request.getRequestDispatcher("/WEB-INF/admin/jsp/login.jsp").forward(
				request, response);
	}

	public void _info() throws Exception {
		request.setAttribute("tUser", tUserDao.info(tUser.getId()));
		request.getRequestDispatcher("/WEB-INF/admin/jsp/myInfo/info.jsp")
				.forward(request, response);
	}

	public void _mUpdate() throws Exception {
		String url = request.getParameter("url");
		if ("update".equals(url)) {
			request.setAttribute("tUser", tUserDao.info(tUser.getId()));
			request
					.getRequestDispatcher(
							"/WEB-INF/admin/jsp/myInfo/update.jsp").forward(
							request, response);
		} else {
			if ("pass".equals(url)) {
				request.getRequestDispatcher(
						"/WEB-INF/admin/jsp/myInfo/updatePass.jsp").forward(
						request, response);
			} else {
				if ("uPass".equals(url)) {
					if (this.updatePass()) {
						request.getRequestDispatcher(
								"/WEB-INF/admin/jsp/right.jsp").forward(
								request, response);
					} else {
						request.getRequestDispatcher("/error/error.jsp")
								.forward(request, response);
					}
				}
				StringBuffer msg = new StringBuffer();
				msg.append("{\"id\":" + tUser.getId() + "");
				tUserDao.update(tUser);
				msg.append(",\"msg\":\"null\"}");
				response.getWriter().write(msg.toString());
				response.getWriter().close();
			}
		}
	}

	private boolean updatePass() throws Exception {
		String oldPass = request.getParameter("oldPass");
		tUser = tUserDao.info(tUser.getId());
		if (!Md5.validPassword(oldPass, tUser.getPassword())) {
			request.setAttribute("message", "旧密码不正确");
			return false;
		} else {
			String newPass_1 = request.getParameter("newPass_1");
			String newPass_2 = request.getParameter("newPass_2");
			if (newPass_1 == null || newPass_2 == null
					|| newPass_1.trim().length() == 0
					|| newPass_2.trim().length() == 0) {
				request.setAttribute("message", "新密码不能为空");
				return false;
			} else {
				if (!newPass_1.equals(newPass_2)) {
					request.setAttribute("message", "密码和确认密码不匹配");
					return false;
				} else {
					tUserDao.updatePass(newPass_1, tUser.getId());
					return true;
				}
			}
		}
	}
}
